// 运行时配置
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
import avatar from '@/assets/avatar.ico';
import { history } from '@@/exports';
import { RunTimeLayoutConfig } from '@umijs/max';
import { message } from 'antd';
import Footer from './components/Footer';
import { getUserInfoApi } from './services/user/UserController';
import { getToken } from './utils/operateToken';

type ErrorInfo = {
  message: string;
  time: string;
  path: string;
  status: number;
};

export async function getInitialState(): Promise<{
  user_id?: number;
  email?: string;
  username?: string;
  nickname?: string;
}> {
  let userInfo = {};
  const token = getToken();
  if (token) {
    try {
      const { data } = await getUserInfoApi();
      userInfo = data;
      if (location.pathname === '/login') {
        history.replace('/');
      }
    } catch (error) {
      if (location.pathname !== '/login') {
        history.replace('/login');
      }
    }
  } else {
    if (location.pathname !== '/login') {
      history.replace('/login');
    }
  }
  return userInfo;
}

export const layout: RunTimeLayoutConfig = () => {
  return {
    title: 'Reindeerの后台',
    logo: avatar,
    menu: {
      locale: false,
    },
    footerRender: () => <Footer />,
    layout: 'side',
    // 配合 <PageContainer /> 才会显示面包屑
    breadcrumbRender: (items) => {
      // return items;
      return [];
    },
    breadcrumbProps: {
      separator: '>',
    },
    // 去掉菜单栏下面信息
    rightContentRender: false,
  };
};

// 配置请求响应拦截器
export const request = {
  timeout: 2000,
  // 请求拦截器
  requestInterceptors: [
    function (url: string, options: any) {
      // 从本地获取 token
      const token = getToken();
      if (token) {
        options.headers['Authorization'] = 'Bearer ' + token;
      }
      return { url, options };
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    async function (response: any) {
      return response;
    },
  ],
  errorConfig: {
    // 错误接收及处理
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;
      if (error.response && error.response.data) {
        // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        message.error(error.response.data.message);
        if (
          error.response.data.status == 401 &&
          location.pathname !== '/login'
        ) {
          history.replace('/login');
        }
      } else if (error.request) {
        // 请求已经成功发起，但没有收到响应
        message.error('None response! Please retry.');
      } else {
        // 发送请求时出了点问题
        message.error('Request error, please retry.');
      }
    },
  },
};
